package com.lanhai.longheng.listener;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Component;
 
import com.lanhai.longheng.dispatch.DispatchDevice; 
 

/** 
 * 收取来自对接设备的消息
 * @author virus408
 *
 */
@Component
public class DeviceListener {
	@Autowired 
	DispatchDevice dispaD;
	
 
	 
	private boolean running;
	private Thread th;
	
	public void Start(int port) {
		running=true;
		th=new Thread() { 
			@Override
			public void run() {
				try{ 
					DatagramSocket	ds = new DatagramSocket(port);
					while(running){
						byte buf[] = new byte[20];
						DatagramPacket dp = new DatagramPacket(buf, buf.length);
						ds.receive(dp);
					  
						if(buf.length>6) {
							dispaD.resolve(dp.getAddress().getHostAddress(),buf);
							//dispaD.resolve("172.16.110.196",buf);
						}
					}	
					ds.close();
				}catch(Exception e){
					e.printStackTrace();
				}	
			}
			
		};
		th.start();
	}
	
	
	
	public void Stop() {
		running=false;
		try {
			th.interrupt();
			th=null; 
		}catch(Exception e) { 
		}
	}
}
